package com.xin.di.uav.applet.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xin.di.uav.applet.mapper.ErrandOrderMapper;
import com.xin.di.uav.applet.po.ErrandOrder;
import com.xin.di.uav.applet.resp.ErrandOrderResp;
import com.xin.di.uav.applet.service.IErrandOrderService;
import com.xin.di.uav.common.enums.PaymentMethodEnum;
import com.xin.di.uav.common.enums.TcOrderStatusEnum;
import com.xin.di.uav.common.request.operate.ErrandOrderReq;
import com.xin.di.uav.common.utils.PhoneEncoderUtil;
import com.xin.di.uav.common.utils.RespJsonPageData;
import com.xin.di.uav.common.utils.Rs;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 跑腿订单 服务实现类
 * </p>
 *
 * @author LTQ
 * @since 2024-09-12
 */
@RequiredArgsConstructor
@Service
public class ErrandOrderServiceImpl extends ServiceImpl<ErrandOrderMapper, ErrandOrder> implements IErrandOrderService {

    private final ErrandOrderMapper errandOrderMapper;
    private final PhoneEncoderUtil phoneEncoderUtil;


    @Override
    public RespJsonPageData<ErrandOrderResp> getErrandOrderList(ErrandOrderReq errandOrderReq) {
        Boolean isErrand = ObjectUtil.isNotNull(errandOrderReq.getStatus()) && !TcOrderStatusEnum.NOT_TC.getStatus().equals(errandOrderReq.getStatus());
        Boolean isFlag = ObjectUtil.isNotNull(errandOrderReq.getStatus()) && TcOrderStatusEnum.NOT_TC.getStatus().equals(errandOrderReq.getStatus());
        //分页查询
        Page<ErrandOrder> page = this.page(new Page<>(errandOrderReq.getPage(), errandOrderReq.getSize()),
                new LambdaQueryWrapper<ErrandOrder>()
                        .like(StrUtil.isNotBlank(errandOrderReq.getTcWayBillNo()), ErrandOrder::getErrandOrderSn, errandOrderReq.getTcWayBillNo())
                        .like(StrUtil.isNotBlank(errandOrderReq.getFyWayBillNo()), ErrandOrder::getOrderSn, errandOrderReq.getFyWayBillNo())
                        .ge(StrUtil.isNotBlank(errandOrderReq.getOrderStartDate()), ErrandOrder::getCreateTime, errandOrderReq.getOrderStartDate())
                        .le(StrUtil.isNotBlank(errandOrderReq.getOrderEndDate()), ErrandOrder::getCreateTime, errandOrderReq.getOrderEndDate())
                        .eq(isErrand, ErrandOrder::getStatus, errandOrderReq.getStatus())
                        .and(isErrand, item -> item.isNotNull(ErrandOrder::getLatitude).isNotNull(ErrandOrder::getErrandOrderSn))
                        .isNull(isFlag, ErrandOrder::getErrandOrderSn)
                        .isNull(isFlag, ErrandOrder::getLatitude)
                        .orderByDesc(ErrandOrder::getCreateTime));
        //判空
        if (CollUtil.isEmpty(page.getRecords())) {
            return RespJsonPageData.success(new ArrayList<>(), 0);
        }
        List<ErrandOrderResp> distributionOrderListRes = BeanUtil.copyToList(page.getRecords(), ErrandOrderResp.class);
        //骑手电话脱敏、状态名设置
        distributionOrderListRes.forEach(item -> {
            //订单状态名替换
//            if (ObjectUtil.isEmpty(item.getErrandOrderSn()) && ObjectUtil.isNull(item.getLatitude())) {
            if (ObjectUtil.isEmpty(item.getErrandOrderSn())) {
                item.setStatusName(TcOrderStatusEnum.NOT_TC.getName());
            } else {
                item.setStatusName(TcOrderStatusEnum.getName(item.getStatus()));
            }
            //骑手手机号解密脱敏
            String phone = phoneEncoderUtil.decryptString(item.getRiderPhone());
            item.setRiderPhone(DesensitizedUtil.desensitized(phone, DesensitizedUtil.DesensitizedType.MOBILE_PHONE));
            //金额相关换算
            if (ObjectUtil.isNotEmpty(item.getTotalPaymentAmount())) {
                item.setTotalPaymentAmount(item.getTotalPaymentAmount().divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP));
            }
            if (ObjectUtil.isNotEmpty(item.getPricePaid())) {
                item.setPricePaid(item.getPricePaid().divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP));
            }
            if (ObjectUtil.isNotEmpty(item.getTotalCouponAmount())) {
                item.setTotalCouponAmount(item.getTotalCouponAmount().divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP));
            }
            //结算方式名替换
            if (StrUtil.isNotBlank(item.getPaymentMethod())) {
                if (PaymentMethodEnum.containsByCode(Integer.valueOf(item.getPaymentMethod()))) {
                    item.setPaymentMethod(PaymentMethodEnum.getName(Integer.valueOf(item.getPaymentMethod())));
                }
            }
        });
        return RespJsonPageData.success(distributionOrderListRes, page.getTotal());
    }

    @Override
    public ErrandOrder getByOrderSn(String orderSn, Byte type) {
        QueryWrapper<ErrandOrder> errandOrderQueryWrapper = new QueryWrapper<>();
        errandOrderQueryWrapper.lambda().eq(ErrandOrder::getOrderSn, orderSn).eq(ErrandOrder::getType, type);
        return errandOrderMapper.selectOne(errandOrderQueryWrapper);
    }


    @Override
    public ErrandOrder getByErrandOrderSn(String errandOrderSn) {
        QueryWrapper<ErrandOrder> errandOrderQueryWrapper = new QueryWrapper<>();
        errandOrderQueryWrapper.lambda().eq(ErrandOrder::getErrandOrderSn, errandOrderSn);
        return errandOrderMapper.selectOne(errandOrderQueryWrapper);
    }

    @Override
    public Rs<String> getDecodePhoneById(String id) {
        ErrandOrder errandOrder = this.getById(id);
        if (ObjectUtils.isEmpty(errandOrder)) {
            Rs.failed("订单不存在");
        }
        if (StrUtil.isBlank(errandOrder.getRiderPhone())) {
            Rs.failed("骑手电话不存在");
        }
        return Rs.success(phoneEncoderUtil.decryptString(errandOrder.getRiderPhone()));
    }
}
